package com.xingda.packing.dmds.http;

import com.alibaba.fastjson.JSONObject;
import com.xingda.packing.dmds.config.appset.AppSetUrl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

@Slf4j
public class TokenHttp {

    /**
     * 获取token
     *
     * @return
     */
    public static String getToken() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowStr = sdf.format(new Date());
        String md5Str = Base64.encodeBase64String(DigestUtils.md5Hex("4QrcOUm6Wau+VuBX8g+IPg==" + nowStr).getBytes());
        List<NameValuePair> list = new LinkedList<>();
        BasicNameValuePair param1 = new BasicNameValuePair("userName", "pull");
        BasicNameValuePair param2 = new BasicNameValuePair("ts", nowStr);
        BasicNameValuePair param3 = new BasicNameValuePair("md5str", md5Str);

        System.out.println(nowStr);
        System.out.println(md5Str);

        list.add(param1);
        list.add(param2);
        list.add(param3);
        try {
            JSONObject tokenJson = BaseHttp.get(AppSetUrl.token_url, list);
            if (Objects.nonNull(tokenJson) && "ok".equals(tokenJson.getString("msg"))) {
                return tokenJson.getString("result");
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.error("token 为null!");
        return null;
    }
}
